package com.lianboke.link.ad.updateUtils;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.widget.Toast;

import com.lianboke.link.ad.VolleyUtils.HttpCallBack;
import com.lianboke.link.ad.VolleyUtils.HttpUtil;
import com.lianboke.link.ad.beans.UpdateAppInfoModel;
import com.lianboke.link.ad.common.CommonParams;
import com.lianboke.link.ad.utils.DeviceUtils;
import com.lianboke.link.ad.utils.KLog;
import com.lianboke.link.ad.utils.ToastUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static android.content.Context.BIND_AUTO_CREATE;

/**
 * 升级服务管理类
 * Created by admin on 2017/10/13.
 */

public class UpdateAppManager {
    public static final String LOG_TAG = "check_update";
    private static Context actContext;
    private static UpdateAppManager instance;

    public static volatile  int iUpdateApkCount = 0;//需要升级的数量
    public static volatile  int iUpdateApkIndex =0;//当前升级的坐标

    private Timer timerUpdate ;
    private TimerTask timerTaskUpdate;


    //需要下载的数据列表
    private List<UpdateAppInfoModel> downAppList =  Collections.synchronizedList(new ArrayList<UpdateAppInfoModel>());


    private UpdateDownLoadService.DownloadBinder mDownloadBinder;

    /**
     * 服务连接
     */
    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            KLog.e(LOG_TAG,"--------------------onServiceConnected-------------");
            mDownloadBinder = (UpdateDownLoadService.DownloadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            KLog.e(LOG_TAG,"--------------------onServiceDisconnected-------------");
            mDownloadBinder = null;
        }
    };
    /**
     * 初始化
     * @param context
     */
    public static UpdateAppManager initUpdate(Context context){
        if(instance==null){
            synchronized(UpdateAppManager.class){
                if(instance==null){
                    actContext = context;
                    instance = new UpdateAppManager();
                }
            }
        }
        return instance;
    }

    private UpdateAppManager() {
        timerUpdate = new Timer();
        Intent intent = new Intent(actContext, UpdateDownLoadService.class);
        actContext.startService(intent);
        actContext.bindService(intent, mConnection, BIND_AUTO_CREATE);//绑定服务

    }

    /**
     * 初始化升级任务参数
     */
    public void initTimeTaskUpdateParams(){
        timerTaskUpdate = new TimerTask() {
            @Override
            public void run() {
                KLog.e(LOG_TAG,"--------------------run---------------");
                checkAppUpdateParams();
            }
        };
        if(timerUpdate==null){
            timerUpdate =new Timer();
        }
        timerUpdate.schedule(timerTaskUpdate,CommonParams.CheckUpdateParams.TIMER_DELAY_TIME);

 //       timerUpdate.schedule(timerTaskUpdate,CommonParams.CheckUpdateParams.TIMER_DELAY_TIME,CommonParams.CheckUpdateParams.TIMER_PERIOD_TIME);
    }

    /**
     * 销毁定时检测更新服务
     */
    public void destoryTimeTaskUpdateParams(){
        try {
            if (mConnection != null) {
                actContext.unbindService(mConnection);
            }
        }catch (Exception e){

        }

        try{
            if(timerTaskUpdate!=null){
                timerTaskUpdate.cancel();
            }
        }catch (Exception e){

        }finally {
            timerTaskUpdate = null;
        }
        try{
            if(timerUpdate!=null){
                timerUpdate.cancel();
            }
        }catch (Exception e){

        }finally {
            timerUpdate = null;
        }
        instance = null;
    }


    /**
     * 检查App的版本信息
     */
    private void checkAppUpdateParams(){
        try {
            if(downAppList!=null){
                downAppList.clear();
            }
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("deviceid", DeviceUtils.getImei(actContext));

            if(downAppList!=null){
                downAppList.clear();
            }else{
                downAppList = Collections.synchronizedList(new ArrayList<UpdateAppInfoModel>());
            }
            HttpUtil.getInstance().request_get(CommonParams.URL_WEB_UPDATE, params, new HttpCallBack<List<UpdateAppInfoModel>>() {
                @Override
                public void onSuccess(List<UpdateAppInfoModel> data) {
                    if(data!=null && !data.isEmpty()){
                        for (UpdateAppInfoModel bean: data ) {
                            KLog.e(LOG_TAG,"-----------update_params--------------:"+bean.toString());
                            boolean isUpdata = false;
                            if(AppUtils.hasApp(actContext,bean.getName())){
                                //有，判断是否需要升级
                                KLog.e(LOG_TAG,"-----------update_params-------has app is  yes-------:");
                                int iUpdateFlag = AppUtils.isVersionUpdate(String.valueOf(bean.getVersion()),AppUtils.getPackageInfo(bean.getName(),actContext));
                                if(iUpdateFlag==1){
                                    KLog.e(LOG_TAG,"-----------update_params-------isVersionUpdate is not =------:");
                                    isUpdata = true;
                                }else{
                                    KLog.e(LOG_TAG,"-----------update_params-------isVersionUpdate is  =------:");
                                }
                            }else{
                                KLog.e(LOG_TAG,"-----------update_params-------has app is not-------:");
                                isUpdata = true;
                            }
                            if(isUpdata){
                                downAppList.add(bean);
                            }
                        }
                    }
                    //发送下载数据
                    startApkDownInfo();
                }

                @Override
                public void onFail(String msg) {

                }
            });
        }catch (Exception e){

        }
    }

    /**
     * 开启下载服务
     */
    private void startApkDownInfo() {
        try {
            KLog.e(LOG_TAG,"--------------------startApkDownInfo-----------d----");
            if (downAppList != null && !downAppList.isEmpty()) {
                KLog.e(LOG_TAG,"--------------------startApkDownInfo-----------d--1--");
                KLog.e(LOG_TAG,"--------------------startApkDownInfo-----------downAppList is size:" + downAppList.size());
               //发送升级
                iUpdateApkCount = downAppList.size();
                KLog.e("update_action_log","-----------------:"+iUpdateApkCount);
                Intent mUpdateIntent = new Intent();
                mUpdateIntent.setAction("android.myapp.update.updatestart");
                actContext.sendBroadcast(mUpdateIntent);

                for (UpdateAppInfoModel bean : downAppList) {
                    KLog.e(LOG_TAG,"--------------------startApkDownInfo-----------d--rrr--");
                    if (mDownloadBinder != null) {
                        KLog.e(LOG_TAG,"---------startApkDownInfo-----------mDownloadBinder----is not null--------");
                        KLog.e(LOG_TAG,"-------------startApkDownInfo------------url:"+bean.getDownurl());
                        long downloadId = mDownloadBinder.startDownload(bean.getDownurl());
                        KLog.e(LOG_TAG,"----------startApkDownInfo-----------------:" + downloadId);
                    } else {
                        //升级失败
                        Intent mUpdateIntentFails = new Intent();
                        mUpdateIntentFails.setAction("android.myapp.update.updatefails");
                        actContext.sendBroadcast(mUpdateIntentFails);
                        KLog.e(LOG_TAG,"---------startApkDownInfo-----------mDownloadBinder-----------is null --");
                    }
                }
            }else{
                //没有需要升级和下载的app
                Intent mUpdateIntentFails = new Intent();
                mUpdateIntentFails.setAction("android.myapp.update.updatenormal");
                actContext.sendBroadcast(mUpdateIntentFails);
                ToastUtil.show(actContext,"恭喜您，当前为最新版本!", Toast.LENGTH_LONG);
            }
        }catch (Exception e){
            //升级失败
            Intent mUpdateIntentFails = new Intent();
            mUpdateIntentFails.setAction("android.myapp.update.updatefails");
            actContext.sendBroadcast(mUpdateIntentFails);
            KLog.e(LOG_TAG,"---------startApkDownInfo-----------mDownloadBinder------Exception------:"+e.getMessage());
        }
    }

}
